package org.quarkus.resources;

import io.smallrye.mutiny.Uni;
import io.vertx.mutiny.pgclient.PgPool;
import io.vertx.mutiny.sqlclient.Tuple;
import lombok.extern.slf4j.Slf4j;
import org.quarkus.entity.User;

import javax.inject.Inject;
import javax.transaction.HeuristicMixedException;
import javax.transaction.HeuristicRollbackException;
import javax.transaction.RollbackException;
import javax.transaction.SystemException;
import javax.transaction.TransactionManager;
import javax.transaction.Transactional;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

/**
 * @Author: TongRui乀
 * @Date: 2021/5/29 10:40
 * @description：
 */
@Slf4j
@Path("user")
@Produces(MediaType.APPLICATION_JSON)
public class UserResource {

    @Inject
    PgPool pgPool;

    @Inject
    TransactionManager tm;


    @POST
    @Consumes(MediaType.APPLICATION_JSON)
    public Uni<User> get(User user){
        return pgPool.preparedQuery("insert into t_user (name, address) values ( $1, $2 ) returning id").execute(Tuple.of(user.getName(), user.getAddress()))
                .onItem()
                .transform(rows->{
                    var id = rows.iterator().next().getLong("id");
                    return id;
                })
                .onItem()
                .transformToUni(id-> this.pgPool.preparedQuery("update t_user set created_time = created_time + interval '1 D' where id = $1").execute(Tuple.of(id))
                        .onItem()
                        .transform(affect->{
                            int a = 1/0;
                            user.setId(id);
                            try {
                                tm.commit();
                            } catch (RollbackException e) {
                                e.printStackTrace();
                            } catch (HeuristicMixedException e) {
                                e.printStackTrace();
                            } catch (HeuristicRollbackException e) {
                                e.printStackTrace();
                            } catch (SystemException e) {
                                e.printStackTrace();
                            }
                            return user;
                        }))
                .onFailure()
                .invoke(e->{
                    try {
                        tm.rollback();
                    } catch (SystemException systemException) {
                        systemException.printStackTrace();
                    }
                    log.error("save or update user error", e);
                });
    }

}
